package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1109. 航班预订统计
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/31 10:42
 */
public class CorpFlightBookings {


    public static void main(String[] args) {
        CorpFlightBookings test = new CorpFlightBookings();

        //输出：[10,55,45,25,25]
        int[][] arr = {{1,2,10},{2,3,20},{2,5,25}};
        int n = 10;

        //输出：[0,55,45,25,25]
//        int[][] arr = {{2,2,10},{2,3,20},{2,5,25}};
//        int n = 10;

        //输出：[10,25]
//        int[][] arr = {{1,2,10},{2,2,15}};
//        int n = 2;


        //[85,100,90,50]
//        int[][] arr = {{2,2,50},{1,1,35},{3,3,40},{1,4,50}};
//        int n = 4;
        int[] ints = test.corpFlightBookings(arr, n);
        System.out.println(Arrays.toString(ints));


    }

    public int[] corpFlightBookings(int[][] bookings, int n) {
        Arrays.sort(bookings, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

        int[] arr = new int[n];
        int length = bookings.length;
        int[][] a1 = new int[length][2];
        int[][] a2 = new int[length][2];
        int index = 0;
        for (int[] booking : bookings) {
            a1[index][0] = booking[0];
            a1[index][1] = booking[2];
            a2[index][0] = booking[1];
            a2[index][1] = booking[2];
            index++;
        }
        Arrays.sort(a1, (a, b) -> a[0] - b[0]);
        Arrays.sort(a2, (a, b) -> a[0] - b[0]);
        int st = 0;
        int end = 0;
        int value = 0;
        for (int i = 0; i < n; i++) {
            for (int j = end; j < length; j++) {
                if (a1[j][0] <= (i + 1)) {
                    value += a1[j][1];
                    end = j + 1;
                } else {
                    break;
                }
            }
            for (int j = st; j < length; j++) {
                if (a2[j][0] < (i + 1)) {
                    value -= a2[j][1];
                    st = j + 1;
                } else {
                    break;
                }
            }
            arr[i] = value;
            if (st >= length) {
                return arr;
            }
        }
        return arr;
    }

}
